package com.kingsoft.dc.khaos.module.mpp.auth;

import com.kingsoft.dc.khaos.extender.meta.model.AuthTable;
import com.kingsoft.dc.khaos.module.mpp.metadata.MppConfig;
import com.kingsoft.dc.khaos.plugin.core.KhaosContext;

import java.util.ArrayList;
import java.util.List;

/**
 * MPP数据整合权限校验
 */
public class MppCombineAuthentication extends MppAuthentication {

    @Override
    public boolean authenticate(KhaosContext kc, Object config) {
        MppConfig mppConfig = (MppConfig)config;
        List<AuthTable> tables = extractAuthTables(mppConfig);
        return checkPriv(tables, kc, mppConfig.getExtender().getAuth().getParams());
    }

    /**
     * 获取要检测的table列表，table信息包含数据库名，数据表名，和操作类型
     * @param mppConfig
     * @return
     */
    public List<AuthTable> extractAuthTables(MppConfig mppConfig) {
        List<AuthTable> tableAuths = new ArrayList<>();
        //源表增量表
        AuthTable t1 = createTableAuth(mppConfig.getSrcSchema(), mppConfig.getSrcTable(), new String[]{DMLType.SELECT.name()});
        //源表减量表
        AuthTable t2 = createTableAuth(mppConfig.getDelSchema(), mppConfig.getDelTable(), new String[]{DMLType.SELECT.name()});

        AuthTable t3 = createTableAuth(mppConfig.getPreSchema(), mppConfig.getPreTable(), new String[]{DMLType.SELECT.name(), DMLType.INSERT.name()});
        AuthTable t4 = createTableAuth(mppConfig.getTarSchema(), mppConfig.getTarTable(), new String[]{DMLType.SELECT.name(), DMLType.INSERT.name()});
        if (t1 != null) {
            tableAuths.add(t1);
        }
        if (t2 != null) {
            tableAuths.add(t2);
        }
        if (t3 != null) {
            tableAuths.add(t3);
        }
        if (t4 != null) {
            tableAuths.add(t4);
        }
        return tableAuths;
    }
}
